package com.elmcode.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.elmcode.server.constant.CartConst;
import com.elmcode.server.entity.FoodEntity;
import com.elmcode.server.exception.BusException;
import com.elmcode.server.exception.ParamsException;
import com.elmcode.server.interceptor.LoginInterceptor;
import com.elmcode.server.service.CartService;
import com.elmcode.server.service.FoodService;
import com.elmcode.server.vo.CartItemVo;
import com.elmcode.server.vo.CartVo;
import com.elmcode.server.vo.CustomerVo;
import io.swagger.models.auth.In;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    FoodService foodService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    private static final String CART_REDIS_KEY = "food:";


    @Override
    public void addOrDelToCart(Long foodId, String flavorItem, String flavorValue, Boolean CartOps) {
        BoundHashOperations<String, String, String> ops = getOps();

        if((!StringUtils.isEmpty(flavorItem) && StringUtils.isEmpty(flavorValue)) ||
                StringUtils.isEmpty(flavorItem) && !StringUtils.isEmpty(flavorValue)){
            throw new ParamsException("参数异常");
        }

        String key = CART_REDIS_KEY + foodId;
        if(!StringUtils.isEmpty(flavorItem)){
            key += ":"+flavorItem+":"+flavorValue;
        }

        // TODO 判断当前顾客的购物车中，是否存在当前商品
        String foodItemStr = ops.get(key);

        if(foodItemStr == null){
            //添加
            FoodEntity foodEntity = foodService.getById(foodId);
            CartItemVo cartItemVo = new CartItemVo();
            BeanUtils.copyProperties(foodEntity,cartItemVo);
            cartItemVo.setCount(1);
            cartItemVo.setFoodId(foodId);
            cartItemVo.setFlavorItem(flavorItem);
            cartItemVo.setFlavorValue(flavorValue);

            String cartItemString = JSON.toJSONString(cartItemVo);
            ops.put(key,cartItemString);

        }else {
            CartItemVo cartItemVo = JSON.parseObject(foodItemStr, CartItemVo.class);
            if(CartOps){//true 表示添加
                //添加 修改
                cartItemVo.setCount(cartItemVo.getCount() + 1);
            }else {
                //删除 修改
                if(cartItemVo.getCount() <= 1){
                    ops.delete(key);
                    return;
                }else {
                    cartItemVo.setCount(cartItemVo.getCount() - 1);
                }
            }
            String s = JSON.toJSONString(cartItemVo);
            ops.put(key,s);
        }
    }

    @Override
    public CartVo getCart() {
        CartVo cartVo = new CartVo();

        List<CartItemVo> cartItems = getCartItems();
        if(cartItems != null){
            cartVo.setCartItemVos(cartItems);
            return cartVo;
        }
        return null;
    }

    @Override
    public void clearCart() {
        CustomerVo customerVo = LoginInterceptor.threadLocal.get();

        //TODO 测试环境，暂时不清空购物车
//        stringRedisTemplate.delete(CartConst.ELM_CART + customerVo.getId());
    }

    private List<CartItemVo> getCartItems() {
        BoundHashOperations<String, String, String> ops = getOps();
        //获取购物车项
        List<String> values = ops.values();

        if(values != null && values.size() > 0){
            List<CartItemVo> collect = values.stream().map(item -> {
                CartItemVo cartItemVo = JSON.parseObject(item, CartItemVo.class);
                return cartItemVo;
            }).collect(Collectors.toList());

            return collect;
        }else {
            return null;
        }
    }

    public BoundHashOperations<String, String, String> getOps() {
        CustomerVo customerVo = LoginInterceptor.threadLocal.get();
        if(customerVo.getId() != null){
            return stringRedisTemplate.boundHashOps(CartConst.ELM_CART + customerVo.getId());
        }
        throw new BusException("购物车操作之前，请登录");
    }
}
